package com.czb.seckill.config;

import com.czb.seckill.pojo.User;
import com.czb.seckill.service.UserService;
import com.czb.seckill.util.CookieUtil;
import com.czb.seckill.vo.RespBean;
import com.czb.seckill.vo.RespBeanEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author: 陈正彬
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            //获取到登入的user对象
            User user = getUser(request, response);
            //存入ThreadLocal
            UserContext.setUser(user);

            //把handler 转成 HandlerMethod
            HandlerMethod hm = (HandlerMethod)handler;
            //获取到目标方法的注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null){ //如果目标方法没有这个注解，说明没有限流防刷
                return true;//继续
            }
            //获取注解的属性值
            int second = accessLimit.second();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
            if (needLogin){//用户必须登入才能访问目标接口/方法
                if (user == null){//用户没有登入
                    render(response,RespBeanEnum.SESSION_ERROR);
                    return false;//返回
                }
            }
            //加入redis计数器，完成对用户限流防刷
            String uri = request.getRequestURI();
            String key = uri + ":" + user.getId();
            ValueOperations valueOperations = redisTemplate.opsForValue();
            Integer count = (Integer) valueOperations.get(key);
            if (count == null){//还没有key，初始化
                valueOperations.set(key,1,second, TimeUnit.SECONDS);
            } else if (count < maxCount) {//正常访问
                valueOperations.increment(key);
            } else {//用户在刷接口
                render(response,RespBeanEnum.ACCESS_LIMIT_REACHED);
                return false;
            }

        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    //方法 得到登入的user对象
    private User getUser(HttpServletRequest request,HttpServletResponse response){
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        if (!StringUtils.hasText(userTicket)) {
            return null; //没有登入
        }
        return userService.getUserByCookie(userTicket,request,response);
    }

    //方法，构建返回对象，以流的形式返回
    private void render(HttpServletResponse response, RespBeanEnum respBeanEnum) throws IOException {

        response.setContentType("application/json");
        response.setCharacterEncoding("utf8");
        PrintWriter writer = response.getWriter();
        //构建RespBean
        RespBean error = RespBean.error(respBeanEnum);
        writer.write(new ObjectMapper().writeValueAsString(error));
        writer.flush();
        writer.close();
    }
}
